require(['MultipleTreeSelect'],function(){
	var roleInfo = {
		initDate: function(e){
			$(e).datetimepicker({//选择年月日
				format: 'yyyy-mm-dd',
				minView: 2, 
			　　　weekStart: 1,
			　　　autoclose: 1,
			　　　todayHighlight: 1,
			　　　startView: 2,
			　　　forceParse: 0
			}).on('hide', function(event) {
				$("#roleGrid").reloadSearchTable();
			});;
		},
		initGrid : function() {
			$('#roleGrid').jqGrid({
				url : "/role/list/page",
				colModel : [
					{name: "id", index: "id", key: true, hidden: true},
					{name: "roleName", label: "角色名称"}, 
					{name: "createTime", label: "创建时间", searchoptions: {dataInit: roleInfo.initDate}},
					{name: "lastUpdateTime", label: "最后更新时间", searchoptions: {dataInit: roleInfo.initDate}},
					{name: "remark", label: "备注"},
					{name: "isOpen", label: "是否启用",stype: 'select',
						searchoptions: {dataUrl:'',buildSelect: function () {
		                    var html = '<select class="form-control">';
		                    html += '<option value="">全部</option>';
	                        html += '<option value="true">已启用</option>';
	                        html += '<option value="false">已禁用</option>';
		                    html += '</select>';
		                    return html;
		                }},
						formatter: function(value, options, row){
							if (value) {
								return '<input name="isOpen" data-id="'+row.id+'" type="checkbox" class="make-switch" checked="checked">';
							}else{
								return '<input name="isOpen" data-id="'+row.id+'" type="checkbox" class="make-switch" >';
							}
						}
				} ],
				search : true,
				autowidth:true,
				height:"100%",
				pager : "#roleGridPager",
				gridComplete: function(){
					$('#roleGrid input[name="isOpen"]').bootstrapSwitch({
						onText: "已启用",
						offText: "已禁用",
						onColor: "success",
						offColor: "default",
						size: "mini",
						onSwitchChange: function(event, state){
							var id = $(this).attr('data-id');
							$.post("/role/save",{id:id,isOpen:state},function(){
								$("#userGrid").reloadTable();
							});  
						}
					});
				}
			});
			roleInfo.initButton();
		},
		initButton : function() {
			$('#roleGrid').jqGrid('filterToolbar');
			$("#sys_role_add").click(function(){
				roleInfo.initDialog(true);
			});
			$("#sys_role_edit").click(function(){
				var id = $('#roleGrid').jqGrid('getGridParam', 'selrow');
				if (!id) {
					toastr.warning("请选择要修改的角色");
					return false;
				}
				roleInfo.initDialog(true, id);
			});
			$("#sys_role_view").click(function(){
				var id = $('#roleGrid').jqGrid('getGridParam', 'selrow');
				if (!id) {
					toastr.warning("请选择要查看的角色");
					return false;
				} 
				roleInfo.initDialog(false, id);
			});
			$("#sys_role_menu_config").click(function(){
				var id = $('#roleGrid').jqGrid('getGridParam', 'selrow');
				if (!id) {
					toastr.warning("请选择要配置的角色");
					return false;
				}
				BootstrapDialog.show({
					title : '菜单配置',
					size : BootstrapDialog.SIZE_NORMAL,
					backDrop : true,
					message : $('<div></div>').load('/fashion/role/menu/config?id='+id),
					buttons : [ {
						id : 'button',
						label : '确定',
						cssClass : 'btn-primary',
						action : function(dialog) {
							var treeObj = $.fn.zTree.getZTreeObj("menuTree");
				            var nodes = treeObj.getCheckedNodes(true);
                            var ids = [];
							$.each(nodes,function(index,node){
								if(node.isLeaf){
                                    ids.push(node.id);
								}
							});
							$.post('/resource/saveRoleResource',{id: id,resourceIds: ids.join(",")},function(data){
								toastr.result(data,function(){
									dialog.close();
									$("#roleGrid").reloadTable();
								});
							});
						}
					}, {
						label : '取消',
						action : function(dialog) {
							dialog.close();
						}
					}]
				});
			});
			$("#sys_role_del").click(function(){
				roleInfo.delRole();
			});
		},
		initDialog : function(isEdit, id) {
			$.get("/role/list/" + id, function(data) {
				BootstrapDialog.show({
					title : '角色信息',
					size : BootstrapDialog.SIZE_NORMAL,
					backdrop : true,
					message : $('<div></div>').load('/fashion/role/save'),
					onshown : function(dialog) {
						if (!isEdit) {
							$("#role_form").readonly();
							$('#role_form [name="isOpen"]').bootstrapSwitch('readonly',true);  
							dialog.getButton('button').disable();
							$("#role_form").readonly();  
						} else {
							roleInfo.validateRole();
						}
						$("#role_form").initForm(data);
					},
					buttons : [
					{
						id : 'button',
						label : '确定',
						cssClass : 'btn-primary',
						action : function(dialog) {
							roleInfo.saveRole(function(){
								dialog.close();
							});
						}
					}, {
						label : '取消',
						action : function(dialog) {
							dialog.close();
						}
					}]
				});
			});
		},
		saveRole : function(callback) {
			var bootstrapValidator = $('#role_form').data('bootstrapValidator');
			bootstrapValidator.validate();
			if (bootstrapValidator.isValid()) {// 如果校验成功后执行的操作
				var json = $('#role_form').serializeObject();
				$.ajax({
					url : '/role/save',
					type : 'post',
					async : false,
					dataType : 'json',
					data : json,
					success : function(data) {
						toastr.result(data,function(){
							callback();
							$("#roleGrid").reloadTable();
						});
					}
				});
			}
		},
		delRole : function() {
			// 获取选中行的id
			var rid = $('#roleGrid').jqGrid('getGridParam', 'selrow');
			if (!rid) {
				toastr.error("请选择要删除的用户");
				return false;
			}
			$.confirm("确定要删除该角色吗",function(){
				$.post("/role/delete", {id : rid}, function(data) {
					toastr.result(data,function(){
						$("#roleGrid").reloadTable();
					});
				});
			});
		},
		// 验证
		validateRole : function() {
			$("#role_form").bootstrapValidator({
				feedbackIcons : {// 根据验证结果显示的各种图标
					valid : 'glyphicon glyphicon-ok',
					invalid : 'glyphicon glyphicon-remove',
					validating : 'glyphicon glyphicon-refresh'
				},
				fields : {
					roleName : {
						validators : {
							notEmpty : {
								message : '角色名称不能为空'
							},
							stringLength : {// 检测长度
								min : 1,
								max : 16,
								message : '长度必须在1-6之间'
							}
						}
					}
				}
			});
		}
	}
	roleInfo.initGrid();
});